import 'package:fate_blind_box/im/entity/addmember_entity.dart';
import 'package:fate_blind_box/im/groupchat.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:roundcheckbox/roundcheckbox.dart';
import '../network/Api.dart';
import '../theme/theme_color.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import '../utils/provider.dart';
import '../widget/icon_text.dart';

//创建群聊
class AddGroupMember extends StatefulWidget {
  String groupid;

  String ouid;

  String type;



  AddGroupMember(this.groupid, this.ouid, this.type, {Key? key})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _AddGroupMemberState();
}

class _AddGroupMemberState extends State<AddGroupMember> {
  final ScrollController _scrollController = ScrollController(); //listview 的控制器
  //List<ContactsBeanComb> _contactList = [];
  bool isLoading = false;
  int _index = 0;
  late List<AddmemberData> addmemberEntity = [];

  final List _listData = [];
  int _pageNum = 1;
  var check = false;

  late String groupId;

  List<String> members = [];

  //是否选中
  bool isSelected = false;
  Color color = Colors.white;

  //完成按钮是否选中
  Color titleColor = const Color(0xffAAA8A8);
  Color backColor = const Color(0xffDDDDDD);

  // String account = SpUtils.getString(CommonUtils.LOGIN_ACCOUNT);

  @override
  void initState() {
    super.initState();

    print('qqq ${widget.type}');
    if (widget.type == '1') {
      //建群进入选择联系人页面，添加被选择的联系人
      members.add(widget.groupid);
      _getListData();
    } else if (widget.type == '2') {
      _getGroupListData();
    }
  }

  _addMamager() async {
    //拉人
    try {
      await EMClient.getInstance.groupManager.addMembers(groupId, members!);
    } on EMError catch (e) {
      if (kDebugMode) {
        print('-----群拉人异常-----------------' + e.toString());
      }
    }
  }

  _removeMamager() async {
    //踢人
    try {
      await EMClient.getInstance.groupManager.removeMembers(groupId, members!);
    } on EMError catch (e) {
      if (kDebugMode) {
        print('-----群踢人异常-----------------' + e.toString());
      }
    }
  }

  _changeOwner() async {
    //变更群主 groupId 群id  newOwner 新管理员
    try {
      // await EMClient.getInstance.groupManager.changeOwner(groupId, members!);
    } on EMError catch (e) {
      if (kDebugMode) {
        print('-----群踢人异常-----------------' + e.toString());
      }
    }
  }

  _getGroup() {
    EMGroupOptions groupOptions = EMGroupOptions(
      style: EMGroupStyle.PublicOpenJoin,
      inviteNeedConfirm: false,
    );
    String groupName = "测试群1";
    String groupDesc = "group desc";

    try {
      EMClient.getInstance.groupManager
          .createGroup(
        groupName: groupName,
        desc: groupDesc,
        options: groupOptions,
      )
          .then((value) {
        print('fff $value');
        groupId = value.groupId;
        if (kDebugMode) {
          print('-----建群id-----------------' + groupId);
        }
      });
    } on EMError catch (e) {
      if (kDebugMode) {
        print('-----建群异常-----------------' + e.toString());
      }
    }
  }

  /// 创建群
  _createGroupData(List members) async {
    final res =
        await Api.getInstance().creatGroup(Provider.userEaseName, members);
    if (res['code'] == 0) {
      Get.to(
          GroupChat(
            res['data'],
            '1',
            isFromChoseContact:true,
          ),
          routeName: PageRouteNames.groupChatPage);
    }
    toast(res['msg']);
  }

  /// 添加群成员
  _addGroupUsersData(List members) async {
    final res = await Api.getInstance().addGroupUsers(widget.groupid, members);
    if (res['code'] == 0) {
      Navigator.pop(context);
    }
    toast(res['msg']);
  }

  /// 获取群拉人时候好友列表数据
  _getGroupListData() async {
    try {
      final easeName = await Provider.getUserEaseName();
      if (kDebugMode) {
        print('rx--环信用户id-------' + Provider.userEaseName);
      }
      if (easeName.isEmpty) return;
      final res = await Api.getInstance()
          .getFriendGroupList(widget.groupid, Provider.userEaseName);

      final data = res['data'];
      if (data != null) {
        List list = data;
        addmemberEntity = AddmemberEntity.fromJson(res).data;
        if (list.isNotEmpty == true) {
          if (_pageNum <= 1) {
            _listData.clear();
          }
          setState(() {
            _listData.addAll(list);
          });
        }
      } else {
        if (kDebugMode) {
          print('------通讯录异常记录---------------' + res['msg']);
        }
      }
    } on EMError catch (e) {
      if (kDebugMode) {
        print('------选择好友列表异常---------------' + e.toString());
      }
    }
  }

  /// 获取建群时候好友列表数据
  _getListData() async {
    try {
      final easeName = await Provider.getUserEaseName();
      if (kDebugMode) {
        print('rx--环信用户id-------' + Provider.userEaseName);
      }
      if (easeName.isEmpty) return;
      final res = await Api.getInstance().getFriendList(Provider.userEaseName);

      final data = res['data'];
      if (data != null) {
        List list = data;
        addmemberEntity = AddmemberEntity.fromJson(res).data;
        if (list.isNotEmpty == true) {
          if (_pageNum <= 1) {
            _listData.clear();
          }
          setState(() {
            _listData.addAll(list);
          });
        }
      } else {
        if (kDebugMode) {
          print('------通讯录异常记录---------------' + res['msg']);
        }
      }
    } on EMError catch (e) {
      if (kDebugMode) {
        print('------选择好友列表异常---------------' + e.toString());
      }
    }
  }

//完成操作
  void _complete() async {
    //已选择的账户
    List<String> selectAccounts = [];

    print('vvv $members');
    if (members.isEmpty || members.length < 2) {
      if (kDebugMode) {
        print('-------请添加好友-----------------');
      }
      return;
    }
    _createGroupData(members);
    // _getGroup();
    // _addMamager();
//  showLoading(context);

    //刷新群聊数据
    print('-------邀请好友成功-----------');

    //Navigator.popUntil(context, ModalRoute.withName(Routes.group_chat_main));
  }

  getCheckBoxBorderColor(int index) {
    if (addmemberEntity[index].isCheck) {
      if (widget.type == '1') {
        if (widget.ouid == addmemberEntity[index].id) {
          return Colors.black12;
        } else {
          return const Color(0xFF3C78FF);
        }
      } else if (widget.type == '2') {
        if (addmemberEntity[index].contain == 1) {
          return Colors.black12;
        } else {
          return const Color(0xFF3C78FF);
        }
      }
    } else {
      return const Color(0xFFD1D1D1);
    }
  }

  Widget _buildSearchBar() {
    return GestureDetector(
      onTap: () {},
      child: Container(
          height: 32,
          margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
          padding: const EdgeInsets.symmetric(horizontal: 24),
          decoration: ShapeDecoration(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(4)),
              color: const Color(0xFFF7F7F7)),
          alignment: Alignment.centerLeft,
          child: IconText(
            "  搜索",
            style: TextStyle(color: ThemeColor.textColorSecond, fontSize: 13),
            icon: const Icon(
              Icons.search_rounded,
              size: 15,
              color: Color(0xFFBABABA),
            ),
            beforeText: true,
          )),
    );
  }

  @override
  Widget build(BuildContext context) {
    Color bgColor = const Color(0xffEDEDED);
    return AppWidget.navTitleBar(
      appBarColor: bgColor,
      title: "选择联系人",
      bgColor: bgColor,
      backAction: () {
        Get.back();
      },
      childWidget: Column(
        children: [
          // _buildSearchBar(),
          // const SizedBox(
          //   height: 10,
          // ),
          Expanded(
              child: Container(
            padding: const EdgeInsets.only(top: 13.0),
            decoration: BoxDecoration(
              //背景
              color: Colors.white,
              //设置四周圆角 角度
              borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(20.0),
                  topRight: Radius.circular(20.0)),
              //设置四周边框
              border: Border.all(width: 1, color: Colors.white),
            ),
            child: ListView.builder(
                itemCount: addmemberEntity.length,
                controller: _scrollController,
                itemBuilder: (context, index) {
                  if (widget.type == '1') {
                    // isRemoveSeleIcon = false;
                    //建群进来
                    if (widget.ouid == addmemberEntity[index].id) {
                      isSelected = true;
                      color = Colors.black12;
                    } else {
                      isSelected = addmemberEntity[index].isCheck;
                      color = Colors.white;
                    }
                  } else if (widget.type == '2') {
                    //"contain": 1   --是否存在群组中  1-是 0-否
                    //拉人进来
                    if (addmemberEntity[index].contain == 1) {
                      isSelected = true;
                      color = Colors.black12;
                      // isRemoveSeleIcon = true;
                    } else {
                      isSelected = addmemberEntity[index].isCheck;
                      color = Colors.white;
                      // isRemoveSeleIcon = false;
                    }
                  }
                  return InkWell(
                    onLongPress: () {
                      if (kDebugMode) {
                        print('-----------------' + index.toString());
                      }
                    },
                    onTap: () {
                      //_goDetails(_contactList[index]);
                      setState(() {
                        if (addmemberEntity[index].isCheck) {
                          addmemberEntity[index].isCheck = false;
                        } else {
                          addmemberEntity[index].isCheck = true;
                        }
                        if (widget.type == '1') {
                          if (widget.ouid != addmemberEntity[index].id) {
                            if (addmemberEntity[index].isCheck) {
                              members?.add(addmemberEntity[index].easeuserId);
                            } else {
                              members
                                  ?.remove(addmemberEntity[index].easeuserId);
                            }
                          }
                        } else if (widget.type == '2') {
                          //"contain": 1   --是否存在群组中  1-是 0-否
                          if (addmemberEntity[index].contain == 0) {
                            if (addmemberEntity[index].isCheck) {
                              members?.add(addmemberEntity[index].easeuserId);
                            } else {
                              members
                                  ?.remove(addmemberEntity[index].easeuserId);
                            }
                          }
                        }

                        if (widget.type == '1') {
                          if (members.length < 2) {
                            titleColor = const Color(0xffAAA8A8);
                            backColor = const Color(0xffDDDDDD);
                          } else {
                            titleColor = Colors.white;
                            backColor = const Color(0xFF7F69D9);
                          }
                        } else if (widget.type == '2') {
                          if (members.length < 1) {
                            titleColor = const Color(0xffAAA8A8);
                            backColor = const Color(0xffDDDDDD);
                          } else {
                            titleColor = Colors.white;
                            backColor = const Color(0xFF7F69D9);
                          }
                        }
                      });
                    },
                    child: Container(
                      decoration: const BoxDecoration(
                          color: Colors.white,
                          border: Border(
                              bottom: BorderSide(
                                  color: Color(0xffd9d9d9), width: 0.3))),
                      padding:
                          const EdgeInsets.only(left: 16, top: 11, bottom: 10),
                      child: Row(
                        children: [
                          RoundCheckBox(
                              size: 24,
                              checkedWidget: const Icon(
                                Icons.check,
                                color: Colors.white,
                                size: 24,
                              ),
                              checkedColor: getCheckBoxBorderColor(index),
                              uncheckedColor: const Color(0x003C78FF),
                              border: Border.all(
                                  color: getCheckBoxBorderColor(index),
                                  width: 1),
                              isChecked: isSelected,
                              onTap: (selected) {
                                check = selected!;
                                addmemberEntity[index].isCheck = check!;
                                setState(() {
                                  if (widget.type == '1') {
                                    if (widget.ouid !=
                                        addmemberEntity[index].id) {
                                      if (addmemberEntity[index].isCheck) {
                                        members?.add(
                                            addmemberEntity[index].easeuserId);
                                      } else {
                                        members?.remove(
                                            addmemberEntity[index].easeuserId);
                                      }
                                    }
                                  } else if (widget.type == '2') {
                                    //"contain": 1   --是否存在群组中  1-是 0-否
                                    if (addmemberEntity[index].contain == 0) {
                                      if (addmemberEntity[index].isCheck) {
                                        members?.add(
                                            addmemberEntity[index].easeuserId);
                                      } else {
                                        members?.remove(
                                            addmemberEntity[index].easeuserId);
                                      }
                                    }
                                  }

                                  if (widget.type == '1') {
                                    if (members.length < 2) {
                                      titleColor = const Color(0xffAAA8A8);
                                      backColor = const Color(0xffDDDDDD);
                                    } else {
                                      titleColor = Colors.white;
                                      backColor = const Color(0xFF7F69D9);
                                    }
                                  } else if (widget.type == '2') {
                                    if (members.length < 1) {
                                      titleColor = const Color(0xffAAA8A8);
                                      backColor = const Color(0xffDDDDDD);
                                    } else {
                                      titleColor = Colors.white;
                                      backColor = const Color(0xFF7F69D9);
                                    }
                                  }
                                });
                              }),
                          Container(
                            padding: const EdgeInsets.only(left: 15),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(5),
                              child: Image.network(
                                addmemberEntity[index].profilePhoto,
                                width: 40,
                                height: 40,
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                          const SizedBox(
                            width: 12,
                          ),
                          Text(
                            addmemberEntity[index].nickName,
                            maxLines: 1,
                            style: const TextStyle(
                                fontSize: 16,
                                color: Colors.black,
                                fontWeight: FontWeight.normal),
                          ),
                          const Expanded(child: Text("")),
                        ],
                      ),
                    ),
                  );
                }),
          )),
          Container(
            margin: const EdgeInsets.only(top: 10, bottom: 10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Container(),
                // Container(
                //   width: 148,
                //   height: 32,
                //   decoration: BoxDecoration(
                //     //背景
                //     color: Colors.white,
                //     //设置四周圆角 角度
                //     borderRadius: const BorderRadius.all(Radius.circular(16.0)),
                //     //设置四周边框
                //     border: Border.all(width: 1, color: Colors.white),
                //   ),
                //   child: Row(
                //     mainAxisAlignment: MainAxisAlignment.center,
                //     crossAxisAlignment: CrossAxisAlignment.center,
                //     children: [
                //       const Text(
                //         "分享聊天记录",
                //         style: TextStyle(
                //           color: Color(0xff7F69D9),
                //           fontSize: 16.0,
                //         ),
                //       ),
                //       Container(
                //         padding: const EdgeInsets.only(left: 3.0),
                //         child: const Icon(
                //           Icons.chevron_right,
                //           color: Color(0xff7F69D9),
                //           size: 20.0,
                //         ),
                //       ),
                //     ],
                //   ),
                // ),
                ElevatedButton(
                    style: ElevatedButton.styleFrom(
                        backgroundColor: backColor,
                        textStyle: const TextStyle(fontSize: 20)),
                    onPressed: () {
                      if (members.length >= 2 && widget.type == '1') {
                        _complete();
                      } else if (members.length >= 1 && widget.type == '2') {
                        print('xxx $members');
                        _addGroupUsersData(members);
                      }
                    },
                    child: Text(
                      "完成",
                      style: TextStyle(color: titleColor),
                    ))
              ],
            ),
          ),
        ],
      ),
    );
  }
}
